package com.wangyk.rabbitmqcommon.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 设置Cookie的方法
 */
public class CookieUtil
{
    /**
     * 给返回的Response设置Cookies
     */
    public static void set(HttpServletResponse response, String name, String value, Integer maxAge)
    {
        //设置Cookie的名称和值
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    /**
     * 获取Cookie
     */
    public static Cookie get(HttpServletRequest request, String name)
    {
        Cookie[] cookies = request.getCookies();
        Cookie cookieResult = null;
        if (null == cookies)
        {
            return null;
        }
        for (Cookie cookie : cookies)
        {
            /**
             * 遍历所有的cookie，查询是否存在已经登录过的
             * */
            if (name.equals(cookie.getName()))
            {
                cookieResult = cookie;
                return cookieResult;
            }
        }
        return cookieResult;
    }
}
